//index.js
//获取应用实例
const app = getApp();

Page({
    data: {
        jieShow: true,
        waitShow: false,
        xiuShow: false,
        username: '',
        timer: '00:00:00',
        runTimer: true,
        orderId: 0,
    },
    onLoad: function (options) {
        if(typeof options.id != 'undefined') {
            this.setData({
                orderId: options.id
            })
        }
        this.timer();
        this.websocket();
    },
    onHide: function () {
    },

    timer: function() {
        var _this = this;
        var time = this.data.timer;
        var timeArr = time.split(':');
        var hour = timeArr[0];
        var minute = timeArr[1];
        var second = timeArr[2];
        var t = setInterval(function(){
            if(!_this.data.runTimer) {
                clearInterval(t);
                return;
            }
            if(second == 59) {
                minute = parseInt(minute) + 1;
                second = 0;
            } else {
                second = parseInt(second) + 1;
            }
            _this.setData({
                timer: [hour, minute, second].map(app.util.formatNumber).join(':')
            });
        }, 1000)
    },

    websocket: function() {
        var _this = this;
        wx.onSocketMessage(function(res){
            var data = JSON.parse(res.data);
            if(data.type == 1) {
                // 超时自动取消订单
                _this.setData({
                    jieShow: false,
                    waitShow: false,
                    xiuShow: true,
                    runTimer: false,
                })
            } else if(data.type == 2) {
                // 有人接单
                _this.setData({
                    jieShow: false,
                    waitShow: true,
                    xiuShow: false,
                    runTimer: false,
                    username: data.worker_name
                })
            }
        })
    },

    // 取消订单
    cancel: function() {
        var _this = this;
        var object = {
            url: app.api.url.order.orderCancel,
            data: {order_id: _this.data.orderId},
            success: function(res) {
                if(res.status == 1){
                    //跳回首页
                    app.redirectTo(app.page.home);
                } else {
                    app.showToast(res.info);
                }
            }
        }
        app.request(object);
    },

    goback: function() {
        app.redirectTo(app.page.home);
    },

    orderdetail:function(){
        app.redirectTo(app.page['order']);
    }
    
});
